// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PyColorAttributeList.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>
#include <PyColorAttribute.h>

// ****************************************************************************
// Module: PyColorAttributeList
//
// Purpose:
//   This class contains a list of ColorAttributes.
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a ColorAttributeList.
//
struct ColorAttributeListObject
{
    PyObject_HEAD
    ColorAttributeList *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewColorAttributeList(int);
std::string
PyColorAttributeList_ToString(const ColorAttributeList *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    { // new scope
        int index = 0;
        // Create string representation of colors from atts.
        for(AttributeGroupVector::const_iterator pos = atts->GetColors().begin(); pos != atts->GetColors().end(); ++pos, ++index)
        {
            const ColorAttribute *current = (const ColorAttribute *)(*pos);
            snprintf(tmpStr, 1000, "GetColors(%d).", index);
            std::string objPrefix(prefix + std::string(tmpStr));
            str += PyColorAttribute_ToString(current, objPrefix.c_str(), forLogging);
        }
        if(index == 0)
            str += "#colors does not contain any ColorAttribute objects.\n";
    }
    return str;
}

static PyObject *
ColorAttributeList_Notify(PyObject *self, PyObject *args)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
ColorAttributeList_GetColors(PyObject *self, PyObject *args)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    int index = -1;
    if (args == NULL)
        return PyErr_Format(PyExc_NameError, "Use .GetColors(int index) to get a single entry");
    if (!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "arg must be a single integer index");
    if (index < 0 || (size_t)index >= obj->data->GetColors().size())
        return PyErr_Format(PyExc_ValueError, "index out of range");

    // Since the new object will point to data owned by the this object,
    // we need to increment the reference count.
    Py_INCREF(self);

    PyObject *retval = PyColorAttribute_Wrap(&obj->data->GetColors(index));
    // Set the object's parent so the reference to the parent can be decref'd
    // when the child goes out of scope.
    PyColorAttribute_SetParent(retval, self);

    return retval;
}

PyObject *
ColorAttributeList_GetNumColors(PyObject *self, PyObject *args)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    return PyInt_FromLong((long)obj->data->GetColors().size());
}

PyObject *
ColorAttributeList_AddColors(PyObject *self, PyObject *args)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    PyObject *element = NULL;
    if(!PyArg_ParseTuple(args, "O", &element))
        return NULL;
    if(!PyColorAttribute_Check(element))
        return PyErr_Format(PyExc_TypeError, "expected attr object of type ColorAttribute");
    ColorAttribute *newData = PyColorAttribute_FromPyObject(element);
    obj->data->AddColors(*newData);
    obj->data->SelectColors();
    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
ColorAttributeList_Remove_One_Colors(PyObject *self, int index)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    // Remove in the AttributeGroupVector instead of calling RemoveColors() because we don't want to delete the object; just remove it.
    AttributeGroupVector &atts = obj->data->GetColors();
    AttributeGroupVector::iterator pos = atts.begin();
    // Iterate through the vector "index" times.
    for(int i = 0; i < index; ++i)
        ++pos;

    // If pos is still a valid iterator, remove that element.
    if(pos != atts.end())
    {
        // NOTE: Leak the object since other Python objects may reference it. Ideally,
        // we would put the object into some type of pool to be cleaned up later but
        // this will do for now.
        //
        // delete *pos;
        atts.erase(pos);
    }

    obj->data->SelectColors();
    Py_INCREF(Py_None);
    return Py_None;
}

PyObject *
ColorAttributeList_RemoveColors(PyObject *self, PyObject *args)
{
    int index = -1;
    if(!PyArg_ParseTuple(args, "i", &index))
        return PyErr_Format(PyExc_TypeError, "Expecting integer index");
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    if(index < 0 || index >= obj->data->GetNumColors())
        return PyErr_Format(PyExc_IndexError, "Index out of range");

    return ColorAttributeList_Remove_One_Colors(self, index);
}

PyObject *
ColorAttributeList_ClearColors(PyObject *self, PyObject *args)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)self;
    int n = obj->data->GetNumColors();
    for(int i = 0; i < n; ++i)
    {
        ColorAttributeList_Remove_One_Colors(self, 0);
        Py_DECREF(Py_None);
    }
    Py_INCREF(Py_None);
    return Py_None;
}



PyMethodDef PyColorAttributeList_methods[COLORATTRIBUTELIST_NMETH] = {
    {"Notify", ColorAttributeList_Notify, METH_VARARGS},
    {"GetColors", ColorAttributeList_GetColors, METH_VARARGS},
    {"GetNumColors", ColorAttributeList_GetNumColors, METH_VARARGS},
    {"AddColors", ColorAttributeList_AddColors, METH_VARARGS},
    {"RemoveColors", ColorAttributeList_RemoveColors, METH_VARARGS},
    {"ClearColors", ColorAttributeList_ClearColors, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
ColorAttributeList_dealloc(PyObject *v)
{
   ColorAttributeListObject *obj = (ColorAttributeListObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *ColorAttributeList_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PyColorAttributeList_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "colors") == 0)
        return ColorAttributeList_GetColors(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PyColorAttributeList_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PyColorAttributeList_methods[i].ml_name),
                PyString_FromString(PyColorAttributeList_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PyColorAttributeList_methods, self, name);
}

int
PyColorAttributeList_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;


    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
ColorAttributeList_print(PyObject *v, FILE *fp, int flags)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)v;
    fprintf(fp, "%s", PyColorAttributeList_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
ColorAttributeList_str(PyObject *v)
{
    ColorAttributeListObject *obj = (ColorAttributeListObject *)v;
    return PyString_FromString(PyColorAttributeList_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *ColorAttributeList_Purpose = "This class contains a list of ColorAttributes.";
#else
static char *ColorAttributeList_Purpose = "This class contains a list of ColorAttributes.";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(ColorAttributeListType,         \
                  "ColorAttributeList",           \
                  ColorAttributeListObject,       \
                  ColorAttributeList_dealloc,     \
                  ColorAttributeList_print,       \
                  PyColorAttributeList_getattr,   \
                  PyColorAttributeList_setattr,   \
                  ColorAttributeList_str,         \
                  ColorAttributeList_Purpose,     \
                  ColorAttributeList_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
ColorAttributeList_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &ColorAttributeListType
         || Py_TYPE(other) != &ColorAttributeListType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    ColorAttributeList *a = ((ColorAttributeListObject *)self)->data;
    ColorAttributeList *b = ((ColorAttributeListObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static ColorAttributeList *defaultAtts = 0;
static ColorAttributeList *currentAtts = 0;

static PyObject *
NewColorAttributeList(int useCurrent)
{
    ColorAttributeListObject *newObject;
    newObject = PyObject_NEW(ColorAttributeListObject, &ColorAttributeListType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new ColorAttributeList(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new ColorAttributeList(*defaultAtts);
    else
        newObject->data = new ColorAttributeList;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapColorAttributeList(const ColorAttributeList *attr)
{
    ColorAttributeListObject *newObject;
    newObject = PyObject_NEW(ColorAttributeListObject, &ColorAttributeListType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (ColorAttributeList *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
ColorAttributeList_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewColorAttributeList(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef ColorAttributeListMethods[] = {
    {"ColorAttributeList", ColorAttributeList_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *ColorAttributeListObserver = 0;

std::string
PyColorAttributeList_GetLogString()
{
    std::string s("ColorAttributeList = ColorAttributeList()\n");
    if(currentAtts != 0)
        s += PyColorAttributeList_ToString(currentAtts, "ColorAttributeList.", true);
    return s;
}

static void
PyColorAttributeList_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("ColorAttributeList = ColorAttributeList()\n");
        s += PyColorAttributeList_ToString(currentAtts, "ColorAttributeList.", true);
        cb(s);
    }
}

void
PyColorAttributeList_StartUp(ColorAttributeList *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyColorAttributeList_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(ColorAttributeListObserver == 0)
    {
        ColorAttributeListObserver = new ObserverToCallback(subj,
            PyColorAttributeList_CallLogRoutine, (void *)data);
    }

}

void
PyColorAttributeList_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete ColorAttributeListObserver;
    ColorAttributeListObserver = 0;
}

PyMethodDef *
PyColorAttributeList_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return ColorAttributeListMethods;
}

bool
PyColorAttributeList_Check(PyObject *obj)
{
    return (obj->ob_type == &ColorAttributeListType);
}

ColorAttributeList *
PyColorAttributeList_FromPyObject(PyObject *obj)
{
    ColorAttributeListObject *obj2 = (ColorAttributeListObject *)obj;
    return obj2->data;
}

PyObject *
PyColorAttributeList_New()
{
    return NewColorAttributeList(0);
}

PyObject *
PyColorAttributeList_Wrap(const ColorAttributeList *attr)
{
    return WrapColorAttributeList(attr);
}

void
PyColorAttributeList_SetParent(PyObject *obj, PyObject *parent)
{
    ColorAttributeListObject *obj2 = (ColorAttributeListObject *)obj;
    obj2->parent = parent;
}

void
PyColorAttributeList_SetDefaults(const ColorAttributeList *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new ColorAttributeList(*atts);
}

